[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfoForEntity } from '@growi/core';
  5. import type {
  6. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  7. } from '@growi/core';
  8. import {
  9. isClient, pagePathUtils, pathUtils,
  10. } from '@growi/core/dist/utils';
  11. import ExtensibleCustomError from 'extensible-custom-error';
  12. import type {
  13. GetServerSideProps, GetServerSidePropsContext,
  14. } from 'next';
  15. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  16. import dynamic from 'next/dynamic';
  17. import Head from 'next/head';
  18. import { useRouter } from 'next/router';
  19. import superjson from 'superjson';
  20. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  21. import { PageView } from '~/components/Page/PageView';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. import type { EditorConfig } from '~/interfaces/editor-settings';
  26. import type { IPageGrantData } from '~/interfaces/page';
  27. import type { RendererConfig } from '~/interfaces/services/renderer';
  28. import type { PageModel, PageDocument } from '~/server/models/page';
  29. import type { PageRedirectModel } from '~/server/models/page-redirect';
  30. import {
  31. useCurrentUser,
  32. useIsForbidden, useIsSharedUser,
  33. useIsEnabledStaleNotification, useIsIdenticalPath,
  34. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  35. useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  36. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  37. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  38. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  39. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  40. } from '~/stores/context';
  41. import { useEditingMarkdown } from '~/stores/editor';
  42. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  43. import {
  44. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  45. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  46. } from '~/stores/page';
  47. import { useRedirectFrom } from '~/stores/page-redirect';
  48. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  49. import { useSelectedGrant } from '~/stores/ui';
  50. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  51. import loggerFactory from '~/utils/logger';
  52. import { BasicLayout } from '../components/Layout/BasicLayout';
  53. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  54. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  55. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  56. import type { NextPageWithLayout } from './_app.page';
  57. import type { CommonProps } from './utils/commons';
  58. import {
  59. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  60. } from './utils/commons';
  61. declare global {
  62. // eslint-disable-next-line vars-on-top, no-var
  63. var globalEmitter: EventEmitter;
  64. }
  65. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  66. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  67. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  68. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  69. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  70. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  71. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  72. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  73. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  74. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  75. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  76. const logger = loggerFactory('growi:pages:all');
  77. const {
  78. isPermalink: _isPermalink, isCreatablePage,
  79. } = pagePathUtils;
  80. const { removeHeadingSlash } = pathUtils;
  81. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  82. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  83. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  84. {
  85. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  86. return v?.data != null
  87. && v?.data.toObject != null
  88. && v?.meta != null
  89. && isIPageInfoForEntity(v.meta);
  90. },
  91. serialize: (v) => {
  92. return {
  93. data: superjson.stringify(v.data.toObject()),
  94. meta: superjson.stringify(v.meta),
  95. };
  96. },
  97. deserialize: (v) => {
  98. return {
  99. data: superjson.parse(v.data),
  100. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  101. };
  102. },
  103. },
  104. 'IPageToShowRevisionWithMetaTransformer',
  105. );
  106. // GrowiContextualSubNavigation for NOT shared page
  107. type GrowiContextualSubNavigationProps = {
  108. isLinkSharingDisabled: boolean,
  109. }
  110. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  111. const { isLinkSharingDisabled } = props;
  112. const { data: currentPage } = useSWRxCurrentPage();
  113. return (
  114. <div data-testid="grw-contextual-sub-nav">
  115. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  116. </div>
  117. );
  118. };
  119. type Props = CommonProps & {
  120. pageWithMeta: IPageToShowRevisionWithMeta | null,
  121. // pageUser?: any,
  122. redirectFrom?: string;
  123. // shareLinkId?: string;
  124. isLatestRevision?: boolean,
  125. isIdenticalPathPage?: boolean,
  126. isForbidden: boolean,
  127. isNotFound: boolean,
  128. isNotCreatable: boolean,
  129. // isAbleToDeleteCompletely: boolean,
  130. templateTagData?: string[],
  131. templateBodyData?: string,
  132. isSearchServiceConfigured: boolean,
  133. isSearchServiceReachable: boolean,
  134. isSearchScopeChildrenAsDefault: boolean,
  135. isEnabledMarp: boolean,
  136. isSlackConfigured: boolean,
  137. // isMailerSetup: boolean,
  138. isAclEnabled: boolean,
  139. // hasSlackConfig: boolean,
  140. drawioUri: string | null,
  141. hackmdUri: string,
  142. noCdn: string,
  143. // highlightJsStyle: string,
  144. isAllReplyShown: boolean,
  145. isContainerFluid: boolean,
  146. editorConfig: EditorConfig,
  147. isEnabledStaleNotification: boolean,
  148. isEnabledAttachTitleHeader: boolean,
  149. // isEnabledLinebreaks: boolean,
  150. // isEnabledLinebreaksInComments: boolean,
  151. adminPreferredIndentSize: number,
  152. isIndentSizeForced: boolean,
  153. disableLinkSharing: boolean,
  154. skipSSR: boolean,
  155. ssrMaxRevisionBodyLength: number,
  156. grantData?: IPageGrantData,
  157. rendererConfig: RendererConfig,
  158. };
  159. const Page: NextPageWithLayout<Props> = (props: Props) => {
  160. // register global EventEmitter
  161. if (isClient() && window.globalEmitter == null) {
  162. window.globalEmitter = new EventEmitter();
  163. }
  164. const router = useRouter();
  165. useCurrentUser(props.currentUser ?? null);
  166. // commons
  167. useEditorConfig(props.editorConfig);
  168. useCsrfToken(props.csrfToken);
  169. useGrowiCloudUri(props.growiCloudUri);
  170. // page
  171. useIsContainerFluid(props.isContainerFluid);
  172. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  173. useIsForbidden(props.isForbidden);
  174. useIsNotCreatable(props.isNotCreatable);
  175. useRedirectFrom(props.redirectFrom ?? null);
  176. useIsSharedUser(false); // this page cann't be routed for '/share'
  177. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  178. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  179. useIsSearchPage(false);
  180. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  181. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  182. useIsSearchServiceReachable(props.isSearchServiceReachable);
  183. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  184. useIsSlackConfigured(props.isSlackConfigured);
  185. // useIsMailerSetup(props.isMailerSetup);
  186. useIsAclEnabled(props.isAclEnabled);
  187. // useHasSlackConfig(props.hasSlackConfig);
  188. useHackmdUri(props.hackmdUri);
  189. // useNoCdn(props.noCdn);
  190. useDefaultIndentSize(props.adminPreferredIndentSize);
  191. useIsIndentSizeForced(props.isIndentSizeForced);
  192. useDisableLinkSharing(props.disableLinkSharing);
  193. useRendererConfig(props.rendererConfig);
  194. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  195. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  196. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  197. useIsAllReplyShown(props.isAllReplyShown);
  198. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  199. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  200. const { pageWithMeta } = props;
  201. const pageId = pageWithMeta?.data._id;
  202. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  203. const revisionBody = pageWithMeta?.data.revision?.body;
  204. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  205. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  206. useCurrentPathname(props.currentPathname);
  207. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  208. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  209. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  210. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  211. const { mutate: mutateIsNotFound } = useIsNotFound();
  212. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  213. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  214. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  215. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  216. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  217. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  218. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  219. useSetupGlobalSocket();
  220. useSetupGlobalSocketForPage(pageId);
  221. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  222. // Store initial data (When revisionBody is not SSR)
  223. useEffect(() => {
  224. if (!props.skipSSR) {
  225. return;
  226. }
  227. if (currentPageId != null && !props.isNotFound) {
  228. const mutatePageData = async() => {
  229. const pageData = await mutateCurrentPage();
  230. mutateEditingMarkdown(pageData?.revision.body);
  231. };
  232. // If skipSSR is true, use the API to retrieve page data.
  233. // Because pageWIthMeta does not contain revision.body
  234. mutatePageData();
  235. }
  236. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  237. // sync grant data
  238. useEffect(() => {
  239. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  240. mutateSelectedGrant(grantDataToApply);
  241. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  242. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  243. useEffect(() => {
  244. const decodedURI = decodeURI(window.location.pathname);
  245. if (isClient() && decodedURI !== props.currentPathname) {
  246. const { search, hash } = window.location;
  247. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  248. }
  249. }, [props.currentPathname, router]);
  250. // initialize mutateEditingMarkdown only once per page
  251. // need to include useCurrentPathname not useCurrentPagePath
  252. useEffect(() => {
  253. if (props.currentPathname != null) {
  254. mutateEditingMarkdown(revisionBody);
  255. }
  256. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  257. useEffect(() => {
  258. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  259. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  260. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  261. useEffect(() => {
  262. mutateCurrentPageId(pageId ?? null);
  263. }, [mutateCurrentPageId, pageId]);
  264. useEffect(() => {
  265. mutateIsNotFound(props.isNotFound);
  266. }, [mutateIsNotFound, props.isNotFound]);
  267. useEffect(() => {
  268. mutateIsLatestRevision(props.isLatestRevision);
  269. }, [mutateIsLatestRevision, props.isLatestRevision]);
  270. useEffect(() => {
  271. mutateTemplateTagData(props.templateTagData);
  272. }, [props.templateTagData, mutateTemplateTagData]);
  273. useEffect(() => {
  274. mutateTemplateBodyData(props.templateBodyData);
  275. }, [props.templateBodyData, mutateTemplateBodyData]);
  276. const title = generateCustomTitleForPage(props, pagePath);
  277. return (
  278. <>
  279. <Head>
  280. <title>{title}</title>
  281. </Head>
  282. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  283. <header className="py-0 position-relative">
  284. <div id="grw-subnav-container">
  285. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  286. </div>
  287. </header>
  288. <div className="d-edit-none">
  289. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  290. </div>
  291. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  292. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  293. <DisplaySwitcher
  294. pageView={(
  295. <PageView
  296. pagePath={pagePath}
  297. initialPage={pageWithMeta?.data}
  298. rendererConfig={props.rendererConfig}
  299. />
  300. )}
  301. />
  302. <PageStatusAlert />
  303. </div>
  304. </>
  305. );
  306. };
  307. type LayoutProps = Props & {
  308. children?: ReactNode
  309. }
  310. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  311. const className = useEditorModeClassName();
  312. // init sidebar config with UserUISettings and sidebarConfig
  313. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  314. return (
  315. <BasicLayout className={className}>
  316. {children}
  317. </BasicLayout>
  318. );
  319. };
  320. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  321. return (
  322. <>
  323. <GrowiPluginsActivator />
  324. <DrawioViewerScript />
  325. <Layout {...page.props}>
  326. {page}
  327. </Layout>
  328. <UnsavedAlertDialog />
  329. <DescendantsPageListModal />
  330. <DrawioModal />
  331. <HandsontableModal />
  332. <QuestionnaireModalManager />
  333. <TemplateModal />
  334. <LinkEditModal />
  335. </>
  336. );
  337. };
  338. function getPageIdFromPathname(currentPathname: string): string | null {
  339. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  340. }
  341. class MultiplePagesHitsError extends ExtensibleCustomError {
  342. pagePath: string;
  343. constructor(pagePath: string) {
  344. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  345. this.pagePath = pagePath;
  346. }
  347. }
  348. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  349. const { model: mongooseModel } = await import('mongoose');
  350. const req: CrowiRequest = context.req as CrowiRequest;
  351. const { crowi } = req;
  352. const { revisionId } = req.query;
  353. const Page = crowi.model('Page') as PageModel;
  354. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  355. const { pageService, configManager } = crowi;
  356. let currentPathname = props.currentPathname;
  357. const pageId = getPageIdFromPathname(currentPathname);
  358. const isPermalink = _isPermalink(currentPathname);
  359. const { user } = req;
  360. if (!isPermalink) {
  361. // check redirects
  362. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  363. if (chains != null) {
  364. // overwrite currentPathname
  365. currentPathname = chains.end.toPath;
  366. props.currentPathname = currentPathname;
  367. // set redirectFrom
  368. props.redirectFrom = chains.start.fromPath;
  369. }
  370. // check whether the specified page path hits to multiple pages
  371. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  372. if (count > 1) {
  373. throw new MultiplePagesHitsError(currentPathname);
  374. }
  375. }
  376. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  377. const page = pageWithMeta?.data as unknown as PageDocument;
  378. // add user to seen users
  379. if (page != null && user != null) {
  380. await page.seen(user);
  381. }
  382. // populate & check if the revision is latest
  383. if (page != null) {
  384. page.initLatestRevisionField(revisionId);
  385. props.isLatestRevision = page.isLatestRevision();
  386. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  387. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  388. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  389. }
  390. if (page == null && user != null) {
  391. const templateData = await Page.findTemplate(props.currentPathname);
  392. if (templateData != null) {
  393. props.templateTagData = templateData.templateTags as string[];
  394. props.templateBodyData = templateData.templateBody as string;
  395. }
  396. // apply parent page grant, without groups that user isn't related to
  397. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  398. if (ancestor != null) {
  399. const userRelatedGrantedGroups = await pageService.getUserRelatedGrantedGroups(ancestor, user);
  400. props.grantData = {
  401. grant: ancestor.grant,
  402. grantedGroups: userRelatedGrantedGroups.map((group) => {
  403. return {
  404. id: group.item._id,
  405. name: group.item.name,
  406. type: group.type,
  407. };
  408. }),
  409. };
  410. }
  411. }
  412. props.pageWithMeta = pageWithMeta;
  413. }
  414. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  415. const req: CrowiRequest = context.req as CrowiRequest;
  416. const { crowi } = req;
  417. const Page = crowi.model('Page') as PageModel;
  418. const { currentPathname } = props;
  419. const pageId = getPageIdFromPathname(currentPathname);
  420. const isPermalink = _isPermalink(currentPathname);
  421. const page = props.pageWithMeta?.data;
  422. if (props.isIdenticalPathPage) {
  423. props.isNotCreatable = true;
  424. }
  425. else if (page == null) {
  426. props.isNotFound = true;
  427. props.isNotCreatable = !isCreatablePage(currentPathname);
  428. // check the page is forbidden or just does not exist.
  429. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  430. props.isForbidden = count > 0;
  431. }
  432. else {
  433. props.isNotFound = page.isEmpty;
  434. props.isNotCreatable = false;
  435. props.isForbidden = false;
  436. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  437. if (isPermalink && page.isEmpty) {
  438. props.currentPathname = page.path;
  439. }
  440. // /path/to/page ==> /62a88db47fed8b2d94f30000
  441. if (!isPermalink && !page.isEmpty) {
  442. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  443. if (!isToppage) {
  444. props.currentPathname = `/${page._id}`;
  445. }
  446. }
  447. }
  448. }
  449. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  450. // const req: CrowiRequest = context.req as CrowiRequest;
  451. // const { crowi } = req;
  452. // const UserModel = crowi.model('User');
  453. // if (isUserPage(props.currentPagePath)) {
  454. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  455. // if (user != null) {
  456. // props.pageUser = JSON.stringify(user.toObject());
  457. // }
  458. // }
  459. // }
  460. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  461. const req: CrowiRequest = context.req as CrowiRequest;
  462. const { crowi } = req;
  463. const {
  464. searchService, configManager, aclService,
  465. } = crowi;
  466. props.isSearchServiceConfigured = searchService.isConfigured;
  467. props.isSearchServiceReachable = searchService.isReachable;
  468. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  469. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  470. // props.isMailerSetup = mailService.isMailerSetup;
  471. props.isAclEnabled = aclService.isAclEnabled();
  472. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  473. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  474. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  475. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  476. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  477. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  478. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  479. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  480. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  481. props.editorConfig = {
  482. upload: {
  483. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  484. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  485. },
  486. };
  487. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  488. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  489. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  490. props.rendererConfig = {
  491. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  492. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  493. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  494. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  495. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  496. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  497. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  498. // XSS Options
  499. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  500. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  501. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  502. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  503. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  504. };
  505. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  506. }
  507. /**
  508. * for Server Side Translations
  509. * @param context
  510. * @param props
  511. * @param namespacesRequired
  512. */
  513. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  514. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  515. props._nextI18Next = nextI18NextConfig._nextI18Next;
  516. }
  517. const getAction = (props: Props): SupportedActionType => {
  518. if (props.isNotCreatable) {
  519. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  520. }
  521. if (props.isForbidden) {
  522. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  523. }
  524. if (props.isNotFound) {
  525. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  526. }
  527. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  528. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  529. }
  530. return SupportedAction.ACTION_PAGE_VIEW;
  531. };
  532. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  533. const req = context.req as CrowiRequest;
  534. const { user } = req;
  535. const result = await getServerSideCommonProps(context);
  536. // check for presence
  537. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  538. if (!('props' in result)) {
  539. throw new Error('invalid getSSP result');
  540. }
  541. const props: Props = result.props as Props;
  542. if (props.redirectDestination != null) {
  543. return {
  544. redirect: {
  545. permanent: false,
  546. destination: props.redirectDestination,
  547. },
  548. };
  549. }
  550. if (user != null) {
  551. props.currentUser = user.toObject();
  552. }
  553. try {
  554. await injectPageData(context, props);
  555. }
  556. catch (err) {
  557. if (err instanceof MultiplePagesHitsError) {
  558. props.isIdenticalPathPage = true;
  559. }
  560. else {
  561. throw err;
  562. }
  563. }
  564. await injectRoutingInformation(context, props);
  565. injectServerConfigurations(context, props);
  566. await injectNextI18NextConfigurations(context, props, ['translation']);
  567. addActivity(context, getAction(props));
  568. return {
  569. props,
  570. };
  571. };
  572. export default Page;